package do

import (
	"context"
	"micro.area.server/common"
	"micro.area.server/database"
	"micro.area.server/models"
)

// 地区列表
func AreaList(ctx context.Context) ([]*models.AreaList, error) {
	areas := make([]*models.AreaList, 0)

	eg := database.GetDB()
	if eg == nil {
		return areas, common.DBNil
	}

	err := eg.Select("id, parent_id, level, name").Table("vs_area").Limit(20, 0).Find(&areas)
	if err != nil {
		return areas, common.DBErr
	}

	return areas, nil
}

func AreaListMap(ctx context.Context) (map[int32]*models.AreaList, error) {
	areas := make([]*models.AreaList, 0)

	eg := database.GetDB()
	if eg == nil {
		return nil, common.DBNil
	}

	err := eg.Select("id, parent_id, level, name").Table("vs_area").Find(&areas)
	if err != nil {
		return nil, common.DBErr
	}

	areaMap := make(map[int32]*models.AreaList)
	for _, v := range areas {
		areaMap[v.ID] = v
	}
	return areaMap, nil
}

// 创建商圈
func CreateCircle(circle *models.VsBusinessCircle) error {
	eg := database.GetDB()
	if eg == nil {
		return common.DBNil
	}

	afterID, err := eg.Insert(circle)
	if err != nil {
		return err
	}
	if afterID < 1 {
		return common.DBInsertErr
	}

	return nil
}

// 删除商圈
func DeleteCircle(circleIDs []interface{}) error {
	eg := database.GetDB()
	if eg == nil {
		return common.DBNil
	}

	circle := models.VsBusinessCircle{}

	afterID, err := eg.Table("vs_business_circle").In("id", circleIDs).Delete(&circle)
	if err != nil {
		return err
	}
	if afterID < 1 {
		return common.DBDeleteErr
	}

	return nil
}

// 详情
func CircleInfo(circleIDs []interface{}) ([]*models.VsBusinessCircle, error) {
	eg := database.GetDB()
	if eg == nil {
		return nil, common.DBNil
	}

	circles := make([]*models.VsBusinessCircle, 0)

	err := eg.Table("vs_business_circle").In("id", circleIDs).Find(circles)
	if err != nil {
		return nil, err
	}

	return circles, nil
}

// 搜索
func SearchCircle(areaID, isHot int32, limit, offset uint32, circleName string) ([]*models.VsBusinessCircle, int64, error) {
	eg := database.GetDB()
	if eg == nil {
		return nil, 0, common.DBNil
	}

	session := eg.NewSession()

	circles := make([]*models.VsBusinessCircle, 0)
	if areaID > 0 {
		session.Where("area_id = ?", areaID)
	}
	if circleName != "" {
		session.Where("circle_name = ?", circleName)
	}
	if isHot > 0 {
		session.Where("is_hot = ?", isHot)
	}

	session.Limit(int(limit), int(offset))

	count, err := session.FindAndCount(circles)
	if err != nil {
		return nil, 0, err
	}

	return circles, count, nil
}
